from django.contrib.auth import login
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.users import models
from apps.users.models import User
from apps.users.serializer import AdminAuthSerializer, RegisterSerializer


class AuthView(APIView):
    """
    用户认证登录
    1 获取参数
    2 服务器签发
    3 返回应答
    """

    def post(self, request, *args, **kwargs):
        # 上面继承了APIView 传入的视图request对象中是DRF框架提供的Request类
        # 该对象中提供了两个属性一个是data数据（封装了请求体的数据 body，字典）

        print(request.data)
        # 参数是datadict 形式
        username = request.data.get('username')
        password = request.data.get('password')

        # 反序列器-数据校验
        serializer = AdminAuthSerializer(data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)

        # 服务器签发jwt token数据(create)
        serializer.save()
        # print(serializer.data)
        # 返回响应
        return Response(serializer.data, status=200)


class RegisterView(APIView):
    def post(self, request):

        print(request.data)

        username = request.data["username"]
        print(username)

        #  用户名校验
        try:
            user = User.objects.filter(username=username).count()
            if user == 1:
                # 表示用户存在
                return Response(data={"code": 1001, "errmsg": "用户名存在"})

        except Exception as e:
            return Response(data={"code": -4, "errmsg": "数据库操作失败"})

        else:
            # 数据库保存用户注册信息
            user = User.objects.create_user(username=username, password=request.data['password'])
        # 实现状态保持
        login(request, user)

        return Response(status=201, data={"code": 0, "errmsg": "注册成功"})
